package com.eastfair.imaster.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.eastfair.auth.api.AuthServiceFeign;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.OrganizationDTO;
import com.eastfair.auth.dto.UserAccountDto;
import com.eastfair.auth.entity.UserAccount;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.code.ExceptionCode;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.core.utils.StringUtils;
import com.eastfair.imaster.dao.EmployeeMapper;
import com.eastfair.imaster.dto.EmployeeDTO;
import com.eastfair.imaster.entity.Employee;
import com.eastfair.imaster.entity.ExhibitorEmployee;
import com.eastfair.imaster.service.EmployeeService;
import com.eastfair.imaster.service.ExhibitorEmployeeService;
import com.eastfair.imaster.vo.EmployeeVo;
import com.eastfair.projectcore.api.ProjectCoreServiceFeign;
import com.eastfair.core.snowflake.DefaultUidGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.eastfair.core.base.R.SUCCESS_CODE;

/**
 * <p>
 * 业务实现类
 * 公司员工表
 * </p>
 *
 * @author liuxiaobai
 * @date 2021-08-19
 */
@Slf4j
@Service
@DS("#thread.tenant")
public class EmployeeServiceImpl extends SuperServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    ProjectCoreServiceFeign projectCoreServiceFeign;

    @Autowired
    AuthServiceFeign authServiceFeign;

    @Autowired
    UserAccountServiceFeign userAccountServiceFeign;

    @Autowired
    ExhibitorEmployeeService exhibitorEmployeeService;
    /**************sharding 分库分表操作 *****************/
    @Override
    public boolean updateByIdOfShard(Employee entity) {
        UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<>();
        //可将指定字段更新为null
        updateWrapper.lambda().eq(Employee::getProjectId, entity.getProjectId()).eq(Employee::getId, entity.getId());
        entity.setProjectId(null);
        //删除缓存
        //delCache(entity);
        return SqlHelper.retBool(this.getBaseMapper().update(entity, updateWrapper));
    }

    @Override
    protected R<Boolean> handlerSave(Employee model) {
        //项目id
        model.setProjectId(ContextUtil.getProjectId());
        //雪花ID
        model.setId(DefaultUidGenerator.getUidOfProjectId(model.getProjectId()));
        return R.successDef();
    }


    @Override
    public R<EmployeeVo> addUserIdOfCompany(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        employee.setCompanyId(employeeDTO.getCompanyId());
        employee.setUserAccountId(employeeDTO.getUserAccountId());
        List<Employee> employeeList = list(employee, null);
        if (employeeList != null && !employeeList.isEmpty()) {
            //已经存在则不添加
            return R.fail(ExceptionCode.EMPLOYEE_EXIST);
        }
        employee.setIsAdmin(employeeDTO.getIsAdmin());
        if(org.apache.commons.lang3.StringUtils.isNotBlank(employeeDTO.getNickName())){
            employee.setNickName(employeeDTO.getNickName());
        }

        //添加
        save(employee);
        //将用户同步到组织角色里
        OrganizationDTO organizationDTO = new OrganizationDTO();
        organizationDTO.setResourceId(employeeDTO.getCompanyId());
        organizationDTO.setUserIds(Arrays.asList(employeeDTO.getUserAccountId()));
        authServiceFeign.addUseridOfCompany(organizationDTO);

        return R.success(BeanUtil.copyProperties(employee, EmployeeVo.class));
    }

    @Override
    public R breaklUserIdOfCompany(Long companyId, Long employeeUserId) {
        List<Employee> employeeList = list(null, Arrays.asList(employeeUserId));
        if (employeeList != null && !employeeList.isEmpty()) {
            Employee employee = employeeList.get(0);
            employee.setIsDeleted(BusinessConstant.YES);
            updateByIdOfShard(employee);
            //将用户同步到组织角色里
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setResourceId(companyId);
            organizationDTO.setUserIds(Arrays.asList(employee.getUserAccountId()));
            authServiceFeign.removeUseridOfCompany(organizationDTO);
        }
        return R.success();
    }

    @Override
    public R breaklUserIdOfCompany(Long companyId) {
        Employee employee = new Employee();
        employee.setCompanyId(companyId);
        List<Employee> employeeList = list(employee, null);
        if (employeeList != null && !employeeList.isEmpty()) {
            for (Employee employee1 : employeeList) {
                employee1.setIsDeleted(BusinessConstant.YES);
                updateByIdOfShard(employee1);
            }
            //将用户同步到组织角色里
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setResourceId(companyId);
            organizationDTO.setUserIds(employeeList.stream().map(Employee::getUserAccountId).collect(Collectors.toList()));
            authServiceFeign.removeUseridOfCompany(organizationDTO);
        }
        return R.success();
    }

    @Override
    public List<Employee> list(Employee employee, List<Long> ids) {
        //查询
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        if (employee != null) {
            if (employee.getId() != null) {
                queryWrapper.lambda().eq(Employee::getId, employee.getId());
            }
            if (employee.getCompanyId() != null) {
                queryWrapper.lambda().eq(Employee::getCompanyId, employee.getCompanyId());
            }
            if (employee.getUserAccountId() != null) {
                queryWrapper.lambda().eq(Employee::getUserAccountId, employee.getUserAccountId());
            }
        }
        if (ContextUtil.getProjectId() != null) {
            queryWrapper.lambda().eq(Employee::getProjectId, ContextUtil.getProjectId());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(Employee::getId, ids);
        }
        queryWrapper.lambda().eq(Employee::getIsDeleted, BusinessConstant.DELETE_NO);
        List<Employee> companyList = list(queryWrapper);
        return companyList;
    }

    @Override
    public List<EmployeeVo> queryEmployeeOfCompany(EmployeeDTO employeeDTO) {

        List<Employee> employeeList =null;
        if(employeeDTO.getId()!=null){
            employeeList = list(null, Arrays.asList(employeeDTO.getId()));
        }else{
            Employee employee = new Employee();
            employee.setCompanyId(employeeDTO.getCompanyId());
            employee.setIsDeleted(BusinessConstant.NO);
            employeeList = list(employee, null);
        }


        if (employeeList != null && !employeeList.isEmpty()) {
            List<EmployeeVo> employeeVoList = ConvertUtil.convertList(employeeList, EmployeeVo.class);
            List<Long> userIds = employeeVoList.stream().map(EmployeeVo::getUserAccountId).collect(Collectors.toList());
            //筛选展会用户
            userIds = assembleExhibitorUserId(userIds,employeeDTO.getCompanyId(),employeeDTO.getIsExhibitor());
            //查询用户账户信息
            UserAccountDto userAccountDto = new UserAccountDto();
            userAccountDto.setUserIds(userIds);
            R<List<UserAccountVo>> listR = userAccountServiceFeign.querySimpleByIds(userAccountDto);
            if (SUCCESS_CODE == listR.getCode()) {
                List<UserAccountVo> userAccountVoList = listR.getData();
                //整合用户信息
                if (userAccountVoList != null && !userAccountVoList.isEmpty()) {
                    for (UserAccountVo userAccountVo : userAccountVoList) {
                        for (EmployeeVo employeeVo : employeeVoList) {
                            if (employeeVo.getUserAccountId().equals(userAccountVo.getId())) {
                                employeeVo.setEmail(userAccountVo.getEmail());
                                employeeVo.setHeadImg(userAccountVo.getHeadImg());
                                employeeVo.setMobile(userAccountVo.getMobile());
                                employeeVo.setName(userAccountVo.getName());
                                employeeVo.setMobileCountryCode(userAccountVo.getMobileCountryCode());
                            }
                        }
                    }
                }
            }
            //筛选
            if(!StringUtils.isBlank(employeeDTO.getNickName())){
                employeeVoList = employeeVoList.stream().filter(s -> org.apache.commons.lang3.StringUtils.isNotBlank(s.getNickName()) && s.getNickName().indexOf(employeeDTO.getNickName())>-1).collect(Collectors.toList());
            }
            return employeeVoList;
        }
        return null;
    }

    /**
     * 组装展会用户
     * @param userIds
     * @param companyId
     * @param isExhibitor
     * @return
     */
    public List<Long> assembleExhibitorUserId(List<Long> userIds,Long companyId,Integer isExhibitor){
        if(isExhibitor!=null){
            ExhibitorEmployee exhibitorEmployee = new ExhibitorEmployee();
            exhibitorEmployee.setCompanyId(companyId);
            List<ExhibitorEmployee> exhibitorEmployeeList = exhibitorEmployeeService.list(exhibitorEmployee,null);
            if (exhibitorEmployeeList != null && !exhibitorEmployeeList.isEmpty()) {
                List<Long> employeeUserIds = exhibitorEmployeeList.stream().map(ExhibitorEmployee::getUserAccountId).collect(Collectors.toList());
                if(isExhibitor==1){
                    return employeeUserIds;
                }else{
                    userIds.removeAll(employeeUserIds);
                }
            }
        }
        return userIds;
    }
    @Override
    public R changeSysAdmin(Long companyId, Long employeeUserId) {
        Employee employee = new Employee();
        employee.setId(employeeUserId);
        employee.setCompanyId(companyId);
        List<Employee> employeeList = list(employee, null);
        if (employeeList != null && !employeeList.isEmpty()) {
            //修改公司超级管理员
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setResourceId(companyId);
            organizationDTO.setUserId(employeeList.get(0).getUserAccountId());
            authServiceFeign.updUseridOfCompany(organizationDTO);
        }
        return R.success();
    }

    @Override
    public R updateCompanyUser(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        List<Employee>  employeeList = list(null,Arrays.asList(employeeDTO.getId()));
        if (employeeList == null || employeeList.isEmpty()) {
            return R.fail("修改失败");
        }
        employee = employeeList.get(0);
        if(!StringUtils.isBlank(employeeDTO.getNickName())){
            employee.setNickName(employeeDTO.getNickName());
        }
        updateById(employee);
        //修改auth用户信息
        UserAccountDto userAccountDto = new UserAccountDto();
        BeanUtils.copyProperties(employeeDTO,userAccountDto);
        userAccountDto.setId(employee.getUserAccountId());
        userAccountServiceFeign.updateById(userAccountDto);
        return R.success(updateById(employee));
    }

}
